package com.financing.wap.web.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.common.Views;
import com.financing.wap.dto.FaUserDTO;
import com.financing.wap.dto.HybxOrderDTO;
import com.financing.wap.dto.ProductDetailPageDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IHybxOrderService;
import com.financing.wap.service.ISmsService;
import com.financing.wap.service.ISystemService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.impl.SmsServiceImpl;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.HttpRequestDeviceUtils;
import com.financing.wap.util.IPUtil;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.api.SendEmailController;


public class BaseController {
	
	/**
	 * 日志类
	 */
	protected  static Logger log = Logger.getLogger(BaseController.class);
	
	
	public String mongodbUrl = PropertiesUtils.getValue("mongodbUrl");
	
	/**
	 * 查询用户访问的记录
	 */
	public String shopProductRecord = "wapData/shopProductRecord?shopId={0}&pageSize={1}&pageNo={2}&monthStart={3}";
	
	/**
	 * 查询店铺的排行榜
	 */
	public String shopVistSort = "wapData/shopVistSort?startVistDate={0}&endVistDate={1}&limitCount={2}&cjmd={3}";
	
	/**
	 * 查询用户店铺访问单个的排行
	 */
	public String shopUserVistSort = "wapData/shopUserVistSort?shopId={0}&startVistDate={1}&endVistDate={2}&cjmd={3}";
	
	/**
	 * 视图持有声明
	 */
	protected static final Views views = Views.getInstance();
	
	protected ISystemService systemService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IHybxOrderService hybxOrderService;

	private String fyFlag = "RZ";//返佣标识-DL：登陆可见，RZ：认证可见；
	
	/**
	 * 请求跳转
	 * @param url
	 * @return
	 */
	protected String redirct(String url){
		return "redirect:" + url;
	}
	
	/**
	 * 获取系统session
	 * @return
	 */
	protected static Session getSession(){
		return SessionUtil.getSession();
	}
	
	/**
	 * 获取系统session
	 * @return
	 */
	protected static Session getSession(boolean create){
		return SessionUtil.getSession(create);
	}
	
	/**
	 * 设置系统session
	 * @param session
	 */
	protected void setSession(Session session){
		SessionUtil.setSession(session);
	}
	
	/**
	 * 获取容器底层session
	 * @return
	 */
	protected static HttpSession getHttpSession(){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request.getSession(true);
	}
	
	/**
	 * 获取HttpRequest
	 * @return
	 */
	protected static HttpServletRequest getHttpRequest(){
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	/**
	 * 获取otp验证码
	 * @return
	 */
	protected static String getOtpCode(){
		return (String) getSession(true).getAttribute(ISmsService.OTP_CODE);
	}
	
	/**
	 * 获取otp验证码
	 * @return
	 */
	protected static String getOtpCode(String ID){
		return (String) getSession().getAttribute(ISmsService.OTP_CODE + ID);
	}
	
	/**
	 * 获取otp验证码时间
	 * @return
	 */
	protected static Date getOtpCodeTime(String ID,String timeOutType){
		if(ISmsService.OTP_CODE_FIRST_TIME.equals(timeOutType)){
			return (Date) getSession().getAttribute(ISmsService.OTP_CODE_FIRST_TIME + ID);
		}
		if(ISmsService.OTP_CODE_LAST_TIME.equals(timeOutType)){
			return (Date) getSession().getAttribute(ISmsService.OTP_CODE_LAST_TIME + ID);
		}
		return null;
	}
	/**
	 * 判断当前请求的用户是否已经通过FA认证
	 * @return
	 */
	protected static boolean hasFaAuthentication(){
		
		UserDTO user = getSession(true).getUser();
		String role =  (String)MemcacheCacheHelper.mcc.get("userInfo_"+String.valueOf(user.getId()));
		log.info("userid:"+user.getId()+"role   is  "+role);
		if(StringUtils.isEmpty(role)){
			log.info("userid:"+user.getId()+"found role from session!");
			role = user.getRole();
		}
		log.info("role from session userid:"+user.getId()+"role   is  "+role);
		if(user != null &&  StringUtils.isNotEmpty(role) && !StringUtils.equals(role, Constants.STATUS_USER_NEW)){
			return true;
		}else{
			return false;
		}
	}
	
	protected String getTplPath(HttpServletRequest request){
		return HttpRequestDeviceUtils.isMobileDevice(request) ? "" : "pc/";
	}
	
	/**
	 * 进行验证码超时验证
	 * @param mobile 手机号
	 * @param time 分钟数
	 * @return true:超时，false:未超时
	 */
	protected boolean checkOtpCodeTimeOut(String mobile,int time,String timeOutType){
		log.info("begin get opt code time");
		Date otpCodeDateTime = getOtpCodeTime(mobile,timeOutType);
		log.info("begin get opt code time end"+otpCodeDateTime);
		if(otpCodeDateTime==null){
			log.info("==first otpDateTime is null==");
			return true;
		}
		Calendar otpCodeCa = Calendar.getInstance();
		//otp时间
		otpCodeCa.setTime(otpCodeDateTime);
		otpCodeCa.add(Calendar.MINUTE, time);
		Calendar ca= Calendar.getInstance();
		//当前比较时间
		ca.setTime(new Date());
		
		return otpCodeCa.before(ca);
	}
	/**
	 * 进行验证码-验证
	 * @param mobile 手机号
	 * @param vCode 
	 * @param time 超时分钟数
	 * @return Map
	 */
	protected ResultMap checkOtpCode(String mobile, String vCode){
		
		log.info("-------------begin checkOtpCode		----------------");
		ResultMap result = new ResultMap();
		//获取超时分钟数
		Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time"));
		//短信时间倒计时(首次)
		String timeOutType = ISmsService.OTP_CODE_FIRST_TIME;
		//获取 验证码时间
		Date otpCodeDateTime = getOtpCodeTime(mobile,timeOutType);
		
		//参数判断
		if(StringUtil.isNullOrEmptyStr(mobile) || StringUtil.isNullOrEmptyStr(vCode)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("参数缺失");
			return result;
		}
		//如果等于空 就返回OTP校验失败 、不一致 返回OTP校验失败
		if(otpCodeDateTime==null || !vCode.equalsIgnoreCase(getOtpCode(mobile))){
			result.setStatus(ResultMap.STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR);
			result.setMessage("手机验证码不正确！");
		log.info("-------------otpDateTime or vCode error---------------");
		log.info("-------------end  checkOtpCode        ----------------");
			return result;
		}
		//验证码是否超时
		if(DateUtil.timePlusMinutesComparedNow(otpCodeDateTime,activety_otp_time)){
			result.setStatus(ResultMap.STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
			result.setMessage("手机验证码超时！");
		log.info("-------------first otpDateTime is null----------------");
		log.info("-------------end  checkOtpCode        ----------------");
			return result;
		}
		//清除验证码
		 getSession().setAttribute(ISmsService.OTP_CODE_FIRST_TIME + mobile,DateUtil.addMinute(otpCodeDateTime,-activety_otp_time-1));
		
		//返回成功标记
			result.setStatus(STATUS.SUCCESS);
		log.info("-------------"+result.getStatus()+"----------------");
		log.info("-------------end  checkOtpCode     ----------------");
		return result;
	}
	
	/**
	 * 
	
	* @Title: autoLogin
	
	* @Description: 自动登录
	
	* @param @param request
	* @param @param user    设定文件
	
	* @return void    返回类型
	
	* @throws
	 */
	public void autoLogin(HttpServletRequest request, UserDTO user) {
		Session session = getSession(true);
		session.setLogin(true);
		session.setUser(user);
		
		FaUserDTO userTmp = new FaUserDTO();
		userTmp.setId(user.getId());
		userTmp.setLastLoginIP(IPUtil.getRemoteHost(request));
		userTmp.setLastLoginTime(new Date());
		userService.updateFaUserInfo(userTmp);
		
		setSession(session);
	}
	
	
	public ResultMap dohwbxOrder(HybxOrderDTO dto, HttpServletRequest request,
			ResultMap result, UserDTO loginUser) throws Exception {
		List<String> userMoblieList = new ArrayList<String>();
		userMoblieList.add(loginUser.getMobile());
		//当前登录人ID
		String faId = loginUser.getId();
		//手机号取登录人手机号
		dto.setFpHybxPhone(loginUser.getMobile());
		// 添加参数验证 
		if (StringUtils.isBlank(dto.getFpHybxProject())
				|| StringUtils.isBlank(dto.getFpHybxProjectId())) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("参数缺失");
			return result;
		}
		dto.setoMediaSource(StringUtil.isNullOrEmptyStr((String) SessionUtil
				.getSession().getAttribute("mid")) ? Constants.MEDIA_SOURCE_PT
						: (String) SessionUtil.getSession().getAttribute("mid"));
		dto.setFpHybxFaId(faId);
		DTOdateSetUtil.setCreateInfo(dto);
		DTOdateSetUtil.setUpdateInfo(dto);
		hybxOrderService.insertHybxOrder(dto);
		List<String> mobileList = new ArrayList<String>();
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		return result;
	}
	public HashMap<String, String> splitSummary(ProductDetailPageDTO productDTO) {
		//拆分字段
		HashMap<String, String> hm = splitSummary(productDTO.getSummary());
		productDTO.setSummary(com.alibaba.fastjson.JSONArray.toJSONString(hm));
		return hm;
	}
	public HashMap<String, String> splitSummary(String summary) {
		//拆分字段
		HashMap<String, String> hm=new HashMap<String, String>();
		try {
			String regex="<(?!a|p|/p|br).*?>|募集账号：|补充说明：|产品优势：|风险控制：|还款来源：|资金用途：|融资方：|担保方：";
			String tmp2 = summary.replaceAll(regex,"")+"<a na";
			String fetchregex = "me=[\"'](.*?)[\"']>(.*?)<a na";
			List<String> fecthAll =StringUtil.fecthAll(tmp2,fetchregex,2,true);
			String s="^募集账号|^补充说明|^产品优势|^风险控制|^还款来源|^资金用途|^融资方|^担保方|^项目亮点|^风险控制|^管理团队|^投资策略|^其他";
			for (int i = 0; i < fecthAll.size(); i++) {
				String key = fecthAll.get(i).split("====")[0];
				boolean b = fecthAll.get(i).split("====").length>=2;
				String value = b?fecthAll.get(i).split("====")[1]:"";
				value=value.replaceAll(s, "");
				value=value.replace("&nbsp;","  ").replaceAll("<(?!p|/p|br).*?>","");//.replace("</p>","\n");//过滤html 标签空格   换行专程\n
				hm.put(key,value);
			}
			return hm;
		} catch (Exception e) {
			log.error("summary error",e);
		}
		return hm;
	}
	public String getFYflag(){
		//登录可见
		if(fyFlag.equals("DL") ){
			if(getSession(true).getUser() == null){
				return "DL";
			}else{
				return "ZC";
			}
		}else if(fyFlag.equals("RZ") ){
			UserDTO user = getSession(true).getUser();
			if(user == null){
				user = new UserDTO();
			}
			UserDTO reUser = userService.queryUserById(user.getId());
			if( user.getId() == null){
				return "DL";
			}else if(reUser.getRole() != null &&  !"1".equals(reUser.getRole()) & !"98".equals(reUser.getRole()) && !"99".equals(reUser.getRole())){
				return "ZC";
			}else{
				return "RZ";
			}
		}
		//默认  DL
		return "DL";
	}
	
	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })
	public  Map<String, Object> getParameterMap(HttpServletRequest request) {
	    // 参数Map
	    Map properties = request.getParameterMap();
	    // 返回值Map
	    Map<String,Object> returnMap = new HashMap<String,Object> ();
	    Iterator entries = properties.entrySet().iterator();
	    Map.Entry entry;
	    String name = "";
	    String value = "";
	    while (entries.hasNext()) {
	        entry = (Map.Entry) entries.next();
	        name = (String) entry.getKey();
	        Object valueObj = entry.getValue();
	        if(null == valueObj){
	            value = "";
	        }else if(valueObj instanceof String[]){
	            String[] values = (String[])valueObj;
	            for(int i=0;i<values.length;i++){
	                value = values[i] + ",";
	            }
	            value = value.substring(0, value.length()-1);
	        }else{
	            value = valueObj.toString();
	        }
	        returnMap.put(name, value);
	    }
	    return returnMap;
	}
}
